package com.alex.mvppractice.news.widget;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alex.mvppractice.R;
import com.alex.mvppractice.constant.UrlString;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * ***********************************************************
 * author: alex
 * time: 16/7/19 上午11:31
 * name:
 * overview:
 * usage:
 * *************************************************************
 */
public class NewsFragment extends Fragment {


    @InjectView(R.id.tab_layout)
    TabLayout mTabLayout;
    @InjectView(R.id.viewpager)
    ViewPager mViewpager;

    private List<Fragment> mFragments;

    private String[] mTitles = {"头条", "NBA", "汽车", "笑话"};


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        mFragments = new ArrayList<>();
        ButterKnife.inject(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mFragments.add(NewsListFragment.newInstance(UrlString.TOP_ID));
        mFragments.add(NewsListFragment.newInstance(UrlString.NBA_ID));
        mFragments.add(NewsListFragment.newInstance(UrlString.CAR_ID));
        mFragments.add(NewsListFragment.newInstance(UrlString.JOKE_ID));

        mViewpager.setAdapter(new NewsAdapter(getChildFragmentManager()));
        //加载前后页。
        mViewpager.setOffscreenPageLimit(3);
        //设置联动效果
        mTabLayout.setupWithViewPager(mViewpager);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    class NewsAdapter extends FragmentPagerAdapter {

        public NewsAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }
    }

}
